import { RigidBodyRender } from './rigidBodyRender.js'
import * as Matter from 'matter-js'

export class RigidBody {
  constructor(sprite, body, options) {
    let _body = body
    if (!body) {
      _body = Matter.Bodies.rectangle(
        sprite.x,
        sprite.y,
        sprite.texture.width,
        sprite.texture.height
      )
    }
    this.body = _body
    this.sprite = sprite
    this.award = ''
    this.probability = ''
    this.CONFIG_SIZE = options.configSize
    sprite.anchor.x = 0.5
    sprite.anchor.y = 0.5
    this._rigidBody = null
  }
  static create(sprite, body, options) {
    const rigidBody = new RigidBody(sprite, body, options || {})
    rigidBody._rigidBody = rigidBody
    const render = RigidBodyRender.getInstance(options.configSize)
    render.addRigidBody(rigidBody)
    return rigidBody
  }
  loopFunction(cb) {
    const { CONFIG_SIZE } = this
    this.sprite.position.set(this.body.position.x, this.body.position.y)
    this.sprite.rotation = this.body.angle
    // console.log('-->1', cb)
    if (typeof cb === 'function' && this.body.position.y > CONFIG_SIZE.bgImg.height) {
      const render = RigidBodyRender.getInstance()
      render.removeRigidBody(this._rigidBody)
      cb(this.award)
    }
  }
  setPosition(x, y) {
    Matter.Body.setPosition(this.body, { x, y })
    Matter.Body.setVelocity(this.body, { x: 0, y: 0 })
  }
}
